﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Incomings;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage.WarehouseEnum; //编码

namespace ProduceBasicData.Api.Application.Handler.Incomings
{
    /// <summary>
    /// 来料信息新增处理
    /// </summary>
    public class CreateIncomingsHandler : IRequestHandler<CreateIncomingsCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<IncomingMaterials> incom;
        private readonly IMapper mapper;
        private readonly ICodeRuleService codeRuleService;
        private readonly IBaseRespository<StockInOrder> inrepo;
        private readonly IBaseRespository<StockInOrderItem> itemrepo;
        private readonly IBaseRespository<Inventory> erepo;

        public CreateIncomingsHandler(IBaseRespository<IncomingMaterials> incom,
            IMapper mapper, ICodeRuleService codeRuleService,
            IBaseRespository<StockInOrder> inrepo,
            IBaseRespository<StockInOrderItem> itemrepo,
            IBaseRespository<Inventory> erepo)
        {
            this.incom = incom;
            this.mapper = mapper;
            this.codeRuleService = codeRuleService;
            this.inrepo = inrepo;
            this.itemrepo = itemrepo;
            this.erepo = erepo;
        }

        public async Task<ApiResult<int>> Handle(CreateIncomingsCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();

            var model=mapper.Map<IncomingMaterials>(request);

            //编码
            if (string.IsNullOrEmpty(model.IncomingCode))
            {
                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.Material.IncomingMaterials");
                if (!string.IsNullOrEmpty(code))
                {
                    model.IncomingCode = code;
                }
                else
                {
                    model.IncomingCode = $"L{DateTime.Now:yyyyMMddHHmmss}";
                }
            }



            model.EffectiveDate = model.EffectiveDate.GetValueOrDefault().AddDays(1);
            model.ExpirationDate = model.ExpirationDate.GetValueOrDefault().AddDays(1);

            var a= inrepo.GetAll().Count()+1;
            var b = itemrepo.GetAll().Count() + 1;
            var c = erepo.GetAll().Count() + 1;
            var storkin = new StockInOrder()
            {
                Id=Convert.ToInt32(a),
                InType= StockInType.Purchase,
                WarehouseId=1,
                SupplierId=request.SupplierId,
                Status= StockInStatus.Completed,
                ExpectedInDate=DateTime.Now,
                ActualInDate=DateTime.Now,
                Remark="供应商入库",
                CreateName="admin",
                CreateTime=DateTime.Now
            };
            await inrepo.AddAsync(storkin);

            var kc = new Inventory()
            {
                Id = Convert.ToInt32(c),
                Quantity = request.NUmbner,
                MaterialId= request.GroupId,
                WarehouseId=1,
                LocationId=1,
                BatchNumber=request.Batch,
                ProductionDate=request.EffectiveDate,
                ExpirationDate=request.ExpirationDate,
                CreateTime= DateTime.Now,   
                CreateName = "admin",
            };
            await erepo.AddAsync(kc);

            var mo = new StockInOrderItem()
            {
                Id = Convert.ToInt32(b),
                StockInOrderId = storkin.Id,
                MaterialId=request.GroupId,
                Specification=request.Batch,
                PlannedQuantity=10000,
                ActualQuantity=request.NUmbner,
                ProductionDate=request.EffectiveDate,
                ExpirationDate=request.ExpirationDate,
                Remark="供应商采购",
                CreateName = "admin",
                CreateTime=DateTime.Now
            };
            await itemrepo.AddAsync(mo);

            var r=await incom.AddAsync(model);
            if (r > 0)
            {
                res.Data = r;
                res.Code=ApiEnum.Success;
                res.Msg = "添加成功";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "添加失败";
            }
            return res;
        }
    }
}
